< previous page page_161 next page >

Page 161
You saw one approach for stripping the NULL terminator from a string in Puzzle 1, "Where, oh, Where Is that API Call?," in which the Instr() function was used to find the location of the NULL-terminating character and the Left$() function was used to extract the portion of the string before that character. It may have occurred to you that it would be easier to use the Left$() function to extract the string if the API function could tell you how many characters were actually loaded into the buffer.
Seeing that this puzzle seems to be ending with a question anyway, here's another. Why did Microsoft choose to pass the BufferSize parameter by reference in this function? That would allow the function to change the value of the BufferLength variable from the value you provide during the call.2
What about the Result?
You may have noticed that the GetComputerName function in this example was called using the subroutine calling format in which the return value is ignored as shown here:
Call GetComputerName(s$, BufferLength)
API functions always return values indicating whether they succeed or fail. You might think that it is advisable to always check the results of API functions and write code to handle any errors that occur. The advantage of that approach is that your application will be very robust. The disadvantage is that you have to invest additional effort to write code to handle all possible errors.
Now, I would be the last person to discourage you from incorporating good error-handling into your application. But there are cases using the Win32 API when you can create code that is correct by designin which case, additional error handling is wasted effort. This is one of those cases.
The GetComputerName function can fail if you pass invalid parameters, as you saw in this example. But once you have corrected your code so that you always pass a preinitialized string to the function with the correct BufferLength parameter, the function should always work. This is why the shorter subroutine call approach was used in this example.
7017a6ead0e3c4111b47a554df321e9f.gif 7017a6ead0e3c4111b47a554df321e9f.gif
2 You might want to take a look at the value of the BufferLength variable after the function call.

 
< previous page page_161 next page >